package Q28;

/**
 * 实现strStr()
 *
 * @author 23737
 * @time 2021.12.4
 */
public class Test {
    public static void main(String[] args) {

    }
}

/**
 * api调用 毫无意义
 */
class Solution {
    public int strStr(String haystack, String needle) {
        int i = 0;
        i = haystack.indexOf(needle);
        return i;
    }
}

/**
 * KMP算法
 */
class Solution2 {
    public int strStr(String haystack, String needle) {
        if (needle.length() == 0) {
            return 0;
        }
        int[] next = new int[needle.length()];
        getNext(next, needle);
        int j = -1;
        for (int i = 0; i < haystack.length(); i++) {
            while (j >= 0 && haystack.charAt(i) != needle.charAt(j + 1)) {
                j = next[j];
            }
            if (haystack.charAt(i) == needle.charAt(j + 1)) {
                j++;
            }
            if (j == needle.length() - 1) {
                return (i - needle.length() + 1);
            }
        }
        return -1;
    }

    //求解前缀数组
    public void getNext(int[] next, String needle) {
        int j = -1;
        next[0] = j;
        for (int i = 1; i < needle.length(); i++) {
            while (j >= 0 && needle.charAt(i) != needle.charAt(j + 1)) {
                j = next[j];
            }
            if (needle.charAt(i) == needle.charAt(j + 1)) {
                j++;
            }
            next[i] = j;
        }
    }
}